//
//  UIBarButtonItem+LYAdd.m
//  LYDevelopKit
//
//  Created by 李阳 on 2018/5/28.
//

#import "UIBarButtonItem+LYAdd.h"
#import <objc/runtime.h>
#import "LYUIMacros.h"

LYSYNTH_DUMMY_CLASS(UIBarButtonItem_LYAdd)

@implementation UIBarButtonItem (LYAdd)

+ (UIBarButtonItem *)itemWithImage:(UIImage *)image highlightedImage:(UIImage *)highImage handler:(void (^)(UIBarButtonItem *))handler
{
    UIBarButtonItem *item = [[UIBarButtonItem alloc]init];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:image forState:UIControlStateNormal];
    [btn setImage:highImage forState:UIControlStateHighlighted];
    [btn sizeToFit];
    
    SEL sel = @selector(ly_btnClicked:);
    [btn addTarget:item action:sel forControlEvents:UIControlEventTouchUpInside];
    objc_setAssociatedObject(self, sel, handler, OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    item.customView = btn;
    return item;
}

+ (UIBarButtonItem *)itemWithImage:(UIImage *)image selectedImage:(UIImage *)highImage handler:(void (^)(UIBarButtonItem *))handler
{
    UIBarButtonItem *item = [[UIBarButtonItem alloc]init];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:image forState:UIControlStateNormal];
    [btn setImage:highImage forState:UIControlStateSelected];
    [btn sizeToFit];
    
    SEL sel = @selector(ly_btnClicked:);
    [btn addTarget:item action:sel forControlEvents:UIControlEventTouchUpInside];
    objc_setAssociatedObject(self, sel, handler, OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    item.customView = btn;
    return item;
}

+ (UIBarButtonItem *)itemWithBgImage:(UIImage *)image highlightedBgImage:(UIImage *)highImage handler:(void (^)(UIBarButtonItem *))handler
{
    UIBarButtonItem *item = [[UIBarButtonItem alloc]init];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setBackgroundImage:image forState:UIControlStateNormal];
    [btn setBackgroundImage:highImage forState:UIControlStateHighlighted];
    [btn sizeToFit];
    
    SEL sel = @selector(ly_btnClicked:);
    [btn addTarget:item action:sel forControlEvents:UIControlEventTouchUpInside];
    objc_setAssociatedObject(self, sel, handler, OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    item.customView = btn;
    return item;
}

- (void)ly_btnClicked:(UIButton *)button
{
    void(^handler)(UIBarButtonItem *) = objc_getAssociatedObject(self, _cmd);
    !handler ?: handler(self);
}

@end
